package com.linkage.educloud.ah.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.linkage.educloud.ah.R;
import com.linkage.educloud.ah.bean.AdsBean;
import com.zzhou.common.library.util.DisplayUtils;
import com.linkage.educloud.ah.util.ImageLoader;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by 周振 on 2017/6/5.
 */
public class AdsViewPager extends FrameLayout implements ViewPager.OnPageChangeListener {

    private Context context;
    private int totalCount = 10;
    private int showCount;
    private int currentPosition = 0;
    private ViewPager viewPager;
    private LinearLayout carouselLayout;
    //    private Adapter adapter;
    private OnClickItemListener listener;
    private int pageItemWidth;
    private boolean isUserTouched = false;
    private List<AdsBean> args;

    private Timer mTimer = new Timer();
    private MyTimerTask mTimerTask;

    class MyTimerTask extends TimerTask {
        @Override
        public void run() {
            if (!isUserTouched) {
                currentPosition = (currentPosition + 1) % totalCount;
                handler.sendEmptyMessage(100);
            }
        }
    };
    public void cancelTimer() {
        if (this.mTimer != null) {
            this.mTimer.cancel();
        }
    }

    public void startTimer() {
        if (this.mTimer != null) {
            this.mTimer.purge();
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (currentPosition == totalCount - 1) {
                viewPager.setCurrentItem(showCount - 1, false);
            } else {
                viewPager.setCurrentItem(currentPosition);
            }
        }
    };

    public AdsViewPager(Context context) {
        super(context);
        this.context = context;
    }

    public AdsViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }

    public AdsViewPager(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
    }

    private void init() {
        if (mTimer !=null){
            if (mTimerTask != null) {
                mTimerTask.cancel();
            }
        }
        viewPager.setAdapter(null);
        carouselLayout.removeAllViews();
        if (args == null || args.isEmpty()) {
            return;
        }
        int count = args.size();
        showCount = args.size();
        for (int i = 0; i < count; i++) {
            View view = new View(context);
            if (currentPosition == i) {
                view.setPressed(true);
//                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(pageItemWidth + DisplayUtils.dip2px(3), pageItemWidth + DisplayUtils.dip2px(3));
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(pageItemWidth, pageItemWidth);
                params.setMargins(pageItemWidth, 0, 0, 0);
                view.setLayoutParams(params);
            } else {
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(pageItemWidth, pageItemWidth);
                params.setMargins(pageItemWidth, 0, 0, 0);
                view.setLayoutParams(params);
            }
            view.setBackgroundResource(R.drawable.ads_point_icon);
            carouselLayout.addView(view);
        }
        viewPager.setAdapter(new ViewPagerAdapter());
        viewPager.setCurrentItem(0);
        this.viewPager.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_MOVE:
                        isUserTouched = true;
                        break;
                    case MotionEvent.ACTION_UP:
                        isUserTouched = false;
                        break;
                }
                return false;
            }
        });
        mTimerTask = new MyTimerTask();
        mTimer.schedule(mTimerTask, 5000, 5000);
    }

    //    public void setAdapter(Adapter adapter) {
//        this.adapter = adapter;
//        if (adapter != null) {
//            init();
//        }
//    }
    public void setDatas(List<AdsBean> adss) {
        this.args = adss;
        if (adss == null || adss.size() < 1) {
            return;
        }
        init();
    }

    public void setClickListener(OnClickItemListener listener) {
        this.listener = listener;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        View view = LayoutInflater.from(context).inflate(R.layout.view_ads_layout, null);
        this.viewPager = (ViewPager) view.findViewById(R.id.ads_viewpager);
        this.carouselLayout = (LinearLayout) view.findViewById(R.id.ads_tips);
        pageItemWidth = DisplayUtils.dip2px(5);
        this.viewPager.addOnPageChangeListener(this);
        addView(view);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//        Log.d("CarouselView", "onPageScrolled was invoke()");
    }

    @Override
    public void onPageSelected(int position) {
        currentPosition = position;
        int count = carouselLayout.getChildCount();
        for (int i = 0; i < count; i++) {
            View view = carouselLayout.getChildAt(i);
            if (position % showCount == i) {
                view.setSelected(true);
//                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(pageItemWidth + DisplayUtils.dip2px(3), pageItemWidth + DisplayUtils.dip2px(3));
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(pageItemWidth, pageItemWidth);
                params.setMargins(pageItemWidth, 0, 0, 0);
                view.setLayoutParams(params);
            } else {
                view.setSelected(false);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(pageItemWidth, pageItemWidth);
                params.setMargins(pageItemWidth, 0, 0, 0);
                view.setLayoutParams(params);
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
//        Log.d("CarouselView", "onPageScrollStateChanged was invoke()");
    }

    class ViewPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return totalCount;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            position %= showCount;
            View view = LayoutInflater.from(context).inflate(R.layout.view_ads, null);
            ImageView image = view.findViewById(R.id.image);
            final AdsBean bean = args.get(position);
            ImageLoader.loadAds(context, bean.getImgUrl(), image);
            container.addView(view);
            final int index = position;

            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener == null) {
                        Log.e("AdsViewPager", "OnclickItemListener is not definal");
                        return;
                    }
                    listener.onClickView(v, bean);
                }
            });
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public int getItemPosition(Object object) {
            return super.getItemPosition(object);
        }

        @Override
        public void finishUpdate(ViewGroup container) {
            super.finishUpdate(container);
            int position = viewPager.getCurrentItem();
            if (position == 0) {
                position = showCount;
                viewPager.setCurrentItem(position, false);
            } else if (position == totalCount - 1) {
                position = showCount - 1;
                viewPager.setCurrentItem(position, false);
            }
        }
    }

    public interface OnClickItemListener {
        void onClickView(View view, AdsBean bean);
    }
}

